package main

import (
	"flag"
	"fmt"
	"path/filepath"
	"strings"

	"github.com/spf13/viper"
)

// parse yaml.
var (
	file string
)

func main() {
	flag.StringVar(&file, "file", "", "yaml config file")
	flag.Parse()

	if file == "" || flag.NArg() == 0 {
		fmt.Println("usage: myaml -file xxx key")
		return
	}

	// file should be yaml
	ext := strings.ToLower(filepath.Ext(file))

	if !(ext == ".yaml" || ext == ".yml") {
		fmt.Println("file should end with .yaml or .yml")
		return
	}

	viper.SetConfigType("yaml")
	viper.SetConfigFile(file)
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Errorf("read config file error: %w", err)
		return
	}

	key := flag.Arg(0)

	value := viper.Get(key)
	if value != nil {
		fmt.Println(value)
	}
}
